﻿using System.Linq.Expressions;
using SqlSugar;
using Digitalmes.Common.Result;

namespace Digitalmes.Sugar;

/// <summary>
/// 分页扩展
/// </summary>
public static class SugarPageExtensions
{
    /// <summary>
    /// 分页查询
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="query"></param>
    /// <param name="pageIndex">页号</param>
    /// <param name="pageSize">每页尺寸</param>
    /// <returns></returns>
    public static async Task<PageResult<T>> ToPageAsync<T>(this ISugarQueryable<T> query,
        int pageIndex,
        int pageSize)
    {
        RefAsync<int> totalItems = 0;
        var items = await query.ToPageListAsync(pageIndex, pageSize, totalItems);
        var totalPages = (int)Math.Ceiling(totalItems / (double)pageSize);
        return new PageResult<T>()
        {
            Items = items,
            TotalItems = totalItems,
            TotalPages = totalPages,
        };
    }

    public static async Task<PageResult<T>> ToPageAsync<T>(this ISugarQueryable<T> query,
        int pageIndex, int pageSize,
        Expression<Func<T, object>> order, bool isDesc = true)
    {
        return await query.OrderBy(order, isDesc ? OrderByType.Desc : OrderByType.Asc).ToPageAsync(pageIndex, pageSize);
    }
}
